<template>
  <el-card shadow="hover" class="chart-card">
    <template #header>
      <div class="chart-title">{{ title }}</div>
    </template>
    <div class="chart-container" ref="chartRef"></div>
  </el-card>
</template>

<script setup>
import {ref, onMounted, watch, nextTick} from 'vue';
import axios from "axios";

import { onUnmounted, } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  title: String,          // 图表标题
  option: Object,         // ECharts配置项
  loading: Boolean,       // 加载状态
  error: Error            // 错误对象
})

const emit = defineEmits(['retry'])  // 重试事件
const chartRef = ref(null)          // 图表DOM引用
let chartInstance = null             // ECharts实例

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)
  if (props.option) {
    chartInstance.setOption(props.option)
  }
}

// 响应式调整大小
const handleResize = () => {
  chartInstance?.resize()
}

// 生命周期
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  chartInstance?.dispose()
  window.removeEventListener('resize', handleResize)
})

// 监听option变化
watch(() => props.option, (newOption) => {
  if (newOption) {
    chartInstance?.setOption(newOption)
  }
}, { deep: true })
</script>

<style scoped>
.chart-card {
  height: 400px;
}
.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
.chart-container {
  width: 100%;
  height: 350px;
}
</style>